
/**
 * Created by wangjiakun on 2018/3/14 0014.
 */
import React from 'react';
import {connect} from 'react-redux';

import { messages, getApprovelHistory } from 'share/common';
import {
  Input,
  InputNumber,
  Spin,
  Form,
  Tabs,
  Button,
  TimePicker,
  Radio,
  Card,
  Row,
  Col,
  message,
  DatePicker,
  Affix,
  Select,
  Popover,
  Icon,
  Divider
} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;

import moment from 'moment';
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'
import baseService from "share/base.service";

class TravelAirline extends React.Component {

  supply = {};
  searchType = "standard";
  intEnable = true;//是否可选到国际
  clearHistory = false;//是否切换供应商的时候直接清空地址
  startDate = "";
  endDate = "";
  currentStartDate = "";

  constructor(props) {
    super(props);
    this.state = {
      params: {},//接收父组件带来的参数
      editing: false,//区分编辑页还是新建页
      formCtrl: {},//
      promptList: [], //行程提示语的配置
      defaultDate: "" + moment(travelUtil.getDefaultDate(1)).format('YYYY-MM-DD'),
      isLoading: false,//提交是否loading提示
      selectFromCity:{},//选择的出发城市
      selectToCity:{},//选择的目的城市
      discounts: [messages('request.key381'/*所有*/), 1, 2, 3, 4, 5, 6, 7, 8, 9],//折扣
      currencyList: [],//货币列表
    };
  }

  //初始化编辑数据
  componentWillReceiveProps() {
    const {isResetAirline, defaultValue, editAirline} = this.props.params;
    if (isResetAirline) {
      this.resetForm();
      delete this.props.params.isResetAirline;
      return;
    }
    this.startDate = travelUtil.getFormHeadValue(defaultValue, 'start_date');
    this.endDate = travelUtil.getFormHeadValue(defaultValue, 'end_date');
    this.endDate = travelUtil.getAfterDate(1, moment(this.endDate).format('YYYY-MM-DD'));
    const editData = travelUtil.isEmpty(editAirline);
    const {isEmpty, fromCityCode, fromCity, toCityCode, toCity} = editData;
    if (!isEmpty) {
      if (!this.state.editing) {
        this.setState({
          editing: true,
          selectFromCity: {code: fromCityCode, vendorAlias: fromCity},
          selectToCity: {code: toCityCode, vendorAlias: toCity}
        }, () => {
          this.props.form.resetFields();
        });
      }
    }
  }

  componentWillMount() {
    const {defaultValue, travelInfo} = this.props.params;
    const tempMap = travelInfo['customFormPropertyMap'];
    const obj = tempMap['application.property.control.fields.airline'] ? JSON.parse(tempMap['application.property.control.fields.airline']) : travelUtil.getSetDataByTravelType('airline');
    const promptList = tempMap['travel.itinerary.tips'] ? JSON.parse(tempMap['travel.itinerary.tips']) : [];
    this.setState({
      promptList,
      params: this.props.params,
      formCtrl: obj
    });
    this.startDate = travelUtil.getFormHeadValue(defaultValue, 'start_date');
    this.currentStartDate = travelUtil.getFormHeadValue(defaultValue, 'start_date');
    this.endDate = travelUtil.getFormHeadValue(defaultValue, 'end_date');
    this.endDate = travelUtil.getAfterDate(1, moment(this.endDate).format('YYYY-MM-DD'));
    this.getCurrencyList();//获取货币列表
  }

  cfo = travelUtil.createFormOption;

  getCurrencyList(){
    baseService.getAllCurrencyByLanguage('zh_cn', undefined, true).then(res => {
      this.setState({
        currencyList: res.data
      })
    })
  }

  //选择出发城市
  selectFromCity = (cityObj) => {
    this.setState({selectFromCity: cityObj});
  };

  //选择到达城市
  selectToCity = (cityObj) => {
    this.setState({selectToCity: cityObj});
  };

  //交换城市
  exchangeCity = () => {
    const fromCityItem = this.state.selectFromCity;
    const toCityItem = this.state.selectToCity;
    const {setFieldsValue} = this.props.form;
    this.setState({
      selectToCity: fromCityItem,
      selectFromCity: toCityItem
    });
    setFieldsValue({'fromCity': toCityItem.vendorAlias});
    setFieldsValue({'toCity': fromCityItem.vendorAlias});
  };

  //提交
  toSubmit = (e) => {
    e.preventDefault();
    const { getFieldValue } = this.props.form;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.taxTotalAmount == 0) {
          message.error(messages('my-account.key75'/*金额不能为0*/));
          return;
        }
        const {selectFromCity, selectToCity, formCtrl, params, editing} = this.state;
        values.departureDate = moment(moment(values.departureDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        if (formCtrl.fromCity.required && !selectFromCity.vendorAlias) {
          message.error(messages('request.key368'/*出发城市不匹配或未点击选择*/));
          return;
        }
        if (formCtrl.toCity.required && !selectToCity.vendorAlias) {
          message.error(messages('request.key369'/*到达城市不匹配或未点击选择*/));
          return;
        }
        values.fromCity = selectFromCity.vendorAlias;
        values.fromCityCode = selectFromCity.code;
        values.toCityCode = selectToCity.code;
        values.toCity = selectToCity.vendorAlias;
        this.setState({isLoading: true});
        if (!editing) {
          travelService.travelAirlineSubmit(params.oid, [values]).then(res => {
            this.submitFinish(messages('request.key189'/*已保存*/));
          }).catch(err => {
            message.error(err.response.data.message);
            this.setState({isLoading: false});
          });
        } else {
          values.applicationOID = params.oid;
          values.itineraryOID = this.props.params.editAirline.itineraryOID;
          travelService.updateAirline(values).then(res => {
            this.submitFinish(messages('request.key353'/*已更新*/))
          }).catch(err=> {
            message.error(err.response.data.message);
            this.setState({isLoading: false});
          })
        }
      }
    })
  };

  //提交成功提示
  submitFinish = (mes) => {
    this.setState({isLoading: false});
    message.success(mes);
    this.props.form.resetFields();
    this.closeSlide({isOk: true});
  };

  resetForm = () =>{
    this.props.form.resetFields();
    this.currentStartDate = this.startDate;
    delete this.props.params.editAirline;
    this.setState({
      editing: false
    });
  }

  // 关闭侧滑
  closeSlide = (isOk) => {
    this.props.close(isOk);
  };

  disabledDateStart = (current) => {
    let boo = false;
    if (current < moment(this.startDate) || current >= moment(this.endDate)) {
      boo = true;
    }
    return current && boo;
  };

  startDateChange = (e) => {
    this.currentStartDate = e;
  };

  render() {
    const {formCtrl, isLoading, promptList, currencyList} = this.state;
    const {getFieldDecorator} = this.props.form;
    const {editAirline, travelInfo: {formCode}} = this.props.params;
    const editData = travelUtil.isEmpty(editAirline);
    const TAG = editData.isEmpty;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 10}
    };
    const AirformItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 18}
    };
    const formItemLayoutCity = {
      labelCol: {span: 8},
      wrapperCol: {span: 12}
    }
    const formItemLayoutAmt = {
      labelCol: {span: 4},
      wrapperCol: {span: 20}
    }
    const isCN = this.props.language.code === 'zh_cn'
    const baseCurrency = this.props.company.baseCurrency;
    return (
      <div className="travel-plane">
        <Spin spinning={isLoading}>
          <TravelPrompt promptList={promptList} type={1012} />
          <Form>
            <FormItem className="plane-city-margin">
              <Row>
                <Col span={12}>
                  <FormItem {...formItemLayoutCity} label={messages('request.key376'/*出发城市*/)}>
                    {getFieldDecorator('fromCity', this.cfo(messages('request.key376'/*出发城市*/), {type: 'str', value: editData.fromCity}, !formCtrl.fromCity.required))(
                      <TravelLocation intEnable={this.intEnable}
                                      vendorType={this.searchType}
                                      isEntity={false}
                                      isFlight={true}
                                      formCode={formCode}
                                      onSelect={this.selectFromCity}
                                      isOldDataType={true}/>
                    )}
                  </FormItem>
                  <FormItem {...formItemLayoutCity} label={messages('request.key377'/*到达城市*/)}>
                    {getFieldDecorator('toCity', this.cfo(messages('request.key377'/*到达城市*/), {type: 'str', value: editData.toCity}, !formCtrl.toCity.required))(
                      <TravelLocation intEnable={this.intEnable}
                                      vendorType={this.searchType}
                                      isEntity={false}
                                      isFlight={true}
                                      formCode={formCode}
                                      onSelect={this.selectToCity}
                                      isOldDataType={true}/>
                    )}
                  </FormItem>
                </Col>
                <div className="line-top"></div>
                <Button className={this.props.language.code === 'zh_cn' ? "exchange-city" : "exchange-city-en"}
                        onClick={this.exchangeCity}>{messages('request.key378'/*换*/)}</Button>
                <div className="line-bottom"></div>

                <Col span={12}>
                  <FormItem {...formItemLayoutCity} label={messages('request.key379'/*出发日期*/)}>
                    {getFieldDecorator('departureDate', this.cfo(messages('request.key379'/*出发日期*/), {
                        type: 'moment',
                        value: TAG ? this.startDate : editData.departureDate,
                      }
                    ))
                    (<DatePicker onChange={this.startDateChange} disabledDate={this.disabledDateStart} format="YYYY-MM-DD"/>)}
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
            {
              formCtrl.discount.show &&
              <Row>
                <Col span={24}>
                  <FormItem {...formItemLayout} label={messages('request.key389'/*折扣*/)}>
                    {getFieldDecorator('discount', this.cfo(messages('request.key389'/*折扣*/), {
                      type: 'str',
                      value: String(editData.discount || '')
                    }, !formCtrl.discount.required))
                    (<Input placeholder={messages('common.please.input')/*请输入*/}/>)}
                  </FormItem>
                </Col>
              </Row>
            }

            {
              formCtrl.cabin.show &&
              <Row>
                <Col span={24}>
                  <FormItem {...formItemLayout} label={messages('request.key62'/*舱位*/)}>
                    {getFieldDecorator('cabin', this.cfo(messages('request.key62'/*舱位*/), {
                      type: 'str',
                      value: editData.cabin || (isCN ? '经济舱' : 'Economy class')
                    }, !formCtrl.cabin.required))(
                      <Select getPopupContainer={triggerNode => triggerNode.parentNode}>
                        {travelUtil.getSeatClass(isCN ? 'plane' : 'plane_en').map(seat => <Option value={seat} key={seat}>{seat}</Option>)}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
            }
            {
              formCtrl && formCtrl.optionalReasonOfflineAir && formCtrl.optionalReasonOfflineAir.show &&
              <Row>
                <Col span={24}>
                  <FormItem {...AirformItemLayout} label={messages('mcd.self.flight.reason'/*自选机票理由*/)}>
                    {getFieldDecorator('optionalReasonOfflineAir', this.cfo(messages('mcd.self.flight.reason'/*自选机票理由*/), {
                      type: 'str',
                      value: String(editData.optionalReasonOfflineAir || ''),
                      maxNum: 1000,
                    }, !formCtrl.optionalReasonOfflineAir.required))(
                      <TextArea placeholder={messages('common.please.input')/*请输入*/}/>)}
                  </FormItem>
                </Col>
              </Row>
            }
            {
              formCtrl.taxTotalAmount.show && <Row>
                <FormItem {...formItemLayoutAmt} label={messages('mcd.total.tax.amt'/*含税总金额*/)} required={formCtrl.taxTotalAmount.required}>
                  <Col span={4}>
                    <FormItem>
                      {getFieldDecorator('currency',this.cfo(messages('common.currency'/*币种*/),{type:'str',value:editData.currency || baseCurrency}, !formCtrl.taxTotalAmount.required))(
                        <Select className="for-airline-amt"
                                optionLabelProp="label"
                                getPopupContainer={() => document.getElementsByClassName('for-airline-amt')[0]}>
                          {
                            currencyList.length > 0 && currencyList.map(item => {
                              return <Option key={item.currency} label={item.currency}>{item.currency} {item.currencyName}</Option>
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem>
                      {getFieldDecorator('taxTotalAmount',this.cfo(messages('mcd.total.tax.amt'/*含税总金额*/),{type:'number',value:editData.taxTotalAmount}, !formCtrl.taxTotalAmount.required))(
                        <InputNumber className="train-price" min={0} placeholder={messages('setting.key796'/*请输入金额*/)}/>
                      )}
                    </FormItem>
                  </Col>
                </FormItem>
              </Row>
            }
          </Form>
        </Spin>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button onClick={this.toSubmit} type="primary" loading={isLoading}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.closeSlide}>{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }


}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language
  };
}

const wrappedTravelAirline = Form.create()(TravelAirline);

export default connect(mapStateToProps)(wrappedTravelAirline);
